package models

import (
	"gin-project/config"

	"golang.org/x/crypto/bcrypt"
	"gorm.io/gorm"
)

// User 用户模型
type User struct {
	gorm.Model
	Username string `gorm:"size:50;uniqueIndex;not null" json:"username"`
	Email    string `gorm:"size:100;uniqueIndex;not null" json:"email"`
	Password string `gorm:"size:100;not null" json:"-"`
}

// BeforeSave 保存前的钩子，用于密码加密
func (u *User) BeforeSave(tx *gorm.DB) error {
	// 如果密码有修改，则进行加密
	if len(u.Password) > 0 {
		hashedPassword, err := bcrypt.GenerateFromPassword([]byte(u.Password), bcrypt.DefaultCost)
		if err != nil {
			return err
		}
		u.Password = string(hashedPassword)
	}
	return nil
}
// CheckPassword 验证密码
func(u *User) CheckPassword(password string) bool{
	err := bcrypt.CompareHashAndPassword([]byte(u.Password), []byte(password))
	return err == nil
}

// Create 创建新用户
func CreateUser(user *User) error {
	return config.DB.Create(user).Error
}
// FindByUsername 按用户名查找用户
func GetUserByUsername(username string)(*User,error){
	var user User
	result := config.DB.Where("username = ?", username).First(&user)
	if result.Error !=nil{
		return nil,result.Error
	}
	return &user,nil
}

// MigrateTables 迁移数据表
func MigrateTables() error {
	return config.DB.AutoMigrate(&User{})
}

// GetUserByID 根据ID查询用户
func GetUserById(id uint) (*User,error){
	var user User
	result := config.DB.First(&user,id)
	if result.Error != nil {
		return nil, result.Error
	}
	return &user, nil
}
